import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/auto_router.dart';
import 'package:casdon/common/widget/fullscreen_loading_overlay.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/core/utils/toast_utils.dart';

import 'package:casdon/modules/device/application/notification/scanner_service_notifier.dart';
import 'package:casdon/modules/device/application/notification/product_category_notifier.dart';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class BindUserItem {
  final String encryptedUserIdentifier;
  final String avatar;
  final String nickname;
  final String userType;

  const BindUserItem({
    required this.encryptedUserIdentifier,
    required this.avatar,
    required this.nickname,
    required this.userType,
  });
}

/// 仿原生 BindAccountViewController 的账号选择页
@RoutePage()
class TMBindAccountScreen extends ConsumerStatefulWidget {
  final List<BindUserItem> users;
  final String sessionId;

  const TMBindAccountScreen({
    super.key,
    required this.users,
    required this.sessionId,
  });

  @override
  ConsumerState<TMBindAccountScreen> createState() =>
      _TMBindAccountScreenState();
}

class _TMBindAccountScreenState extends ConsumerState<TMBindAccountScreen> {
  bool _isProcessing = false;

  @override
  Widget build(BuildContext context) {
    return FullscreenLoadingOverlay(
      loading: _isProcessing,
      child: Scaffold(
        appBar: AppBar(
          title: const Text('绑定账号'),
          backgroundColor: Colors.white,
          foregroundColor: Colors.black87,
          elevation: 0,
        ),
        backgroundColor: Colors.white,
        body: ListView.separated(
          padding: EdgeInsets.only(top: 15.h, bottom: 24.h),
          itemBuilder: (context, index) {
            final user = widget.users[index];
            return _buildUserCell(user);
          },
          separatorBuilder: (_, __) => const SizedBox(height: 12),
          itemCount: widget.users.length,
        ),
      ),
    );
  }

  Widget _buildUserCell(BindUserItem user) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 15.w),
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () async {
          await _handleSelect(user);
        },
        child: Container(
          height: 80.h,
          decoration: BoxDecoration(
            color: const Color(0xFFF7F7F7),
            borderRadius: BorderRadius.circular(10.r),
          ),
          padding: EdgeInsets.symmetric(horizontal: 12.w),
          child: Row(
            children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(22.5.r),
                child: Image.network(
                  user.avatar,
                  width: 45.r,
                  height: 45.r,
                  fit: BoxFit.cover,
                  errorBuilder: (_, __, ___) => Container(
                    width: 45.r,
                    height: 45.r,
                    color: Colors.grey.shade300,
                    child: const Icon(Icons.person, color: Colors.white70),
                  ),
                ),
              ),
              SizedBox(width: 15.w),
              Expanded(
                child: Text(
                  user.nickname.isNotEmpty ? user.nickname : '--',
                  style: context.textTheme.bodyLarge?.copyWith(
                    color: context.customColorThemeNonNull.textColor1,
                  ),
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _handleSelect(BindUserItem user) async {
    setState(() => _isProcessing = true);
    try {
      final error = await _bindUser(user);

      if (!mounted) return;
      if (error == null) {
        // 绑定成功，通知扫码流程并展示结果页
        ref.read(tmBindSuccessProvider.notifier).state = true;
      } else {
        TMBindResultRoute(errorMessage: error).push(context);
      }
    } catch (e) {
      if (mounted) ToastUtil.show('绑定失败，请重试');
    } finally {
      if (mounted) setState(() => _isProcessing = false);
    }
  }

  Future<String?> _bindUser(BindUserItem user) async {
    final repo = ref.read(deviceRepositoryProvider);

    if (user.userType == 'taobao') {
      // 淘宝账号走淘宝绑定接口

      try {
        final res = await repo.authLoginWithTaoBaoUserInfo(
          loginStateAccessToken: user.encryptedUserIdentifier,
          sessionId: widget.sessionId,
        );

        if (res == null) return '绑定失败，请稍后重试';
        if (res.success == true) return null;
        return res.message ?? '绑定失败，请稍后重试';
      } catch (e, st) {
        Log.e('绑定天猫账号失败', e, st);
        return '绑定失败，请稍后重试';
      }
    } else {
      // 天猫账号走天猫绑定接口
      try {
        final res = await repo.authLoginWithAliGenieUserInfo(
          loginStateAccessToken: user.encryptedUserIdentifier,
          sessionId: widget.sessionId,
        );

        if (res == null) return '绑定失败，请稍后重试';
        if (res.success == true) return null;
        return res.message ?? '绑定失败，请稍后重试';
      } catch (e, st) {
        Log.e('绑定淘宝账号失败', e, st);
        return '绑定失败，请稍后重试';
      }
    }
  }
}
